# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：baidu_ocr.py
#日期：2019-06-18
#备注：Python利用百度AI进行文字识别, 需要先安装python SDK   pip install baidu-aip
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

from aip import AipOcr
from pycacho.cachobase.file_deal import an_save_txt,get_file
from pycacho.cachobase.deal_json import dict_to_json

# 定义常量
APP_ID = '16552814'
API_KEY = '93R0OpMdmPy31WBBgPEKE1qB'
SECRET_KEY = 'kIClrcGfwFHnWZQjpFYrRmMGG69nChCT'

# 初始化AipFace对象
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

# 打开图片
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


# 调用通用文字识别接口
def basicGeneral(file):
    """ 如果有可选参数 """
    options = {}
    options["detect_direction"] = "true"  # 检测朝向
    options["detect_language"] = "true"  # 检测语言
    result = client.basicGeneral(file, options)
    return(result)


# 通用文字识别（高精度版）
def basicAccurate(file):
    options = {}
    options["detect_direction"] = "true"  # 检测朝向
    options["detect_language"] = "true"   # 检测语言
    result = client.basicAccurate(file, options)
    return (result)


# 识别一些网络上背景复杂，特殊字体的文字。
def webImage(file):
    options = {}
    options["detect_direction"] = "true"  # 检测朝向
    options["detect_language"] = "true"  # 检测语言
    result = client.webImage(file, options)
    return (result)


# 营业执照识别：返回关键字段的值，包括单位名称、地址、成立日期、有效期、法人、注册资本、社会信用代码、类型、组成形式、经营范围、证件编号
def business_license(file):
    b_file = get_file(file)        # 二进制
    result = client.businessLicense(b_file)
    dict_to_json(result)


# 自定义模版识别：templateSign
def custom_ocr(file):
    b_file = get_file(file)
    options = {}
    options["templateSign"] = "01b9dba355fac014130904462e18a6f2"   # 自定义模版
    result = client.custom(b_file,options)
    dict_to_json(result)


def main(file_path):
    file = get_file(file_path)
    result = webImage(file)
    print(result)
    for words in result['words_result']:
        word = words['words']
        print(word)
        an_save_txt('out.txt', word)


if __name__ == '__main__':
    main('H:\\1.png')
    #business_license('ocr/yezz-h.jpg')
    #custom_ocr('ocr/self.png')
